package Pattern.ProxyPattern.Program.programthree;

class AccessValidator {
    public boolean validate(String userId) {
        return true;//身份验证实现代码省略
    }
}

class Logger {
    public void log(String userId) {
        //日志记录实现代码省略
    }
}

interface Searcher {
    public String doSearch(String userId, String keyword);
}

class RealSearcher implements Searcher {
    public String doSearch(String userId, String keyword) {
        return userId+"+"+keyword;//信息查询实现代码省略
    }
}

class ProxySearcher/*(1)*/ implements Searcher{
    private RealSearcher searcher = new RealSearcher();
    private AccessValidator validator;
    private Logger logger;

    public String doSearch(String userId, String keyword) {
        //如果身份验证成功，则执行查询
        if (validate(userId)/*(2)*/) {
            String result = searcher.doSearch(userId, keyword);
            log(userId);/*(3)*/ //记录查询日志
            return result;/*(4)*/ //返回查询结果
        } else {
            return null;
        }
    }

    public boolean validate(String userId) {
        validator = new AccessValidator();
        return validator.validate(userId);/*(5);*/
    }

    public void log(String userId) {
        logger = new Logger();
        logger.log(userId);/*(6);*/
    }
}

class Test {
    public static void main(String args[]) {
        Searcher searcher;/*(7);*/  //针对抽象编程，客户端无须分辨真实主题类和代理类
        searcher = new ProxySearcher();
        String result = searcher.doSearch("Sunny", "Money");
        System.out.println(result);//此处省略后续处理代码
    }
}
